<template>
  <base-breadcrumb :title="$route.meta.title">
    <!-- 专项治理评分管理 -->
    <div id="base-breadcrumb" style="position: relative; overflow: hidden">
      <div id="print-box" style="position: absolute; z-index: -1"></div>
      <!-- 搜索 -->
      <searchData :searchData="searchArr" @search="search"></searchData>
      <!-- 表格 -->
      <a-card :bordered="false">
        <a-row type="flex" style="flex-wrap: nowrap" v-if="hideBuquBtn()">
          <excel ref="exportSelect" :fileName="`项目质量风险评价(${cateName})选中`" is-click-generate="false" :transformTimeKey="[]">
            <a-button
              slot="excelBtn"
              class="excelBtn"
              v-btnPermission="'qm_067_sexp_12'"
              :loading="exportExcelLoading[0]"
              icon="download"
              :disabled="(cate == '100' ? selectedRowKeys100.length < 1 : (cate == '0' ? selectedRowKeys0.length < 1 : selectedRowKeys1.length < 1))"
              type="primary"
              @click="exportExcel(0)"
            >
            选中导出列表
            </a-button>
          </excel>
          <excel
            ref="exportAll"
            :fileName="`项目质量风险评价(${cateName})全部`"
            is-click-generate="false"
            :transformTimeKey="[]"
          >
            <a-button
              slot="excelBtn"
              class="excelBtn"
              v-btnPermission="'qm_067_aexp_13'"
              :loading="exportExcelLoading[1]"
              icon="cloud-download"
              type="primary"
              @click="exportExcel(1)"
            >
              全部导出列表
            </a-button>
          </excel>
          <a-button
            v-btnPermission="'qm_067_sexp_14'" 
            :loading="exportLoading[0]" 
            icon="download" 
            class="ml12" 
            :disabled="(cate == '100' ? selectedRowKeys100.length < 1 : (cate == '0' ? selectedRowKeys0.length < 1 : selectedRowKeys1.length < 1))" 
            type="default" 
            @click="exportWord(0, cate == '100' ? selectedRowKeys100 : (cate == '0' ? selectedRowKeys0 : selectedRowKeys1))"
          >
            选中导出评价信息
          </a-button>
          <a-button
            v-btnPermission="'qm_067_aexp_15'" 
            :loading="exportLoading[1]" 
            icon="cloud-download" 
            class="ml12"
            type="default" 
            @click="exportWord(1)"
          >
            全部导出评价信息
          </a-button>
        </a-row>

        <a-tabs v-model="cate" @change="callback">
          <a-tab-pane v-for="item in tabList" :key="item.id" :tab="item.name" :disabled="!tabStatus">
            <!--Content of Tab Pane 1 数据调用-->
          </a-tab-pane>
        </a-tabs>
        <a-button v-btnPermission="'qm_067_add_01'" v-if="cate == '100' && hideBuquBtn()" class="mb12" icon="plus" type="primary" @click="handleManage(2)"
            :disabled="!tabStatus">新增</a-button>
        <a-button v-btnPermission="'qm_067_add_06'" v-else-if="cate == '0' && hideBuquBtn()" class="mb12" icon="plus" type="primary" @click="handleManage(2)"
            :disabled="!tabStatus">新增</a-button>
        <a-button v-btnPermission="'qm_067_add_09'" v-else-if="cate == '1' && hideBuquBtn()" class="mb12" icon="plus" type="primary" @click="handleManage(2)"
            :disabled="!tabStatus">新增</a-button>
        <!-- 表格 -->
        <list-table 
          ref="table" 
          tableLayout="fixed" 
          size="default" 
          rowKey="id" 
          :row-selection="{ 
            selectedRowKeys: (cate == '100' ? selectedRowKeys100 : (cate == '0' ? selectedRowKeys0 : selectedRowKeys1)), 
            onChange: onSelectChange
          }"
          :columns="cate == '100' ? columns100 : (cate == '0' ? columns0 : columns1)" 
          :request="loadData" 
          :alert="true" 
          show-size-changer 
          show-quick-jumper 
          showPagination="auto"
        >
          <span slot="action" slot-scope="text, record">
            <MoreButton v-if="cate == '100'">
              <!-- 查看 -->
              <a v-btnPermission="'qm_067_loo_05'" @click="handleManage(0, record)">查看</a>
              <!-- 编辑 -->
              <template v-if="(record.status === 'DRAFT' || record.status == 'REJECTED') && hideBuquBtn()">
                <a v-btnPermission="'qm_067_edi_02'" @click="handleManage(1, record)">编辑</a>
              </template>
              <!-- 删除 -->
              <template v-if="record.status === 'DRAFT' && hideBuquBtn()">
                <a v-btnPermission="'qm_067_del_03'" @click="handleRemove(record)">删除</a>
              </template>
              <!-- 当状态为不通过 通过 审批中 有审批详情 --> 
              <template v-if="record.status == 'REJECTED' || record.status == 'SUBMITTED' || record.status == 'PAST'">
                <a-divider v-btnPermission="'qm_067_exa_04'" type="vertical"></a-divider>
                <a v-btnPermission="'qm_067_exa_04'" @click="$bus.$emit('showApprovalDetailsDialog', record.id)">审批详情</a>
              </template>
            </MoreButton>
            <MoreButton v-else-if="cate == '0'">
              <!-- 查看 -->
              <a v-btnPermission="'qm_067_loo_08'" @click="handleManage(0, record)">查看</a>
              <!-- 编辑 -->
              <template v-if="record.status === 'DRAFT' && hideBuquBtn()">
                <a v-btnPermission="'qm_067_edi_07'" @click="handleManage(1, record)">编辑</a>
              </template>
            </MoreButton>
            <MoreButton v-else-if="cate == '1'">
              <!-- 查看 -->
              <a v-btnPermission="'qm_067_loo_11'" @click="handleManage(0, record)">查看</a>
              <!-- 编辑 -->
              <template v-if="record.status === 'DRAFT' && hideBuquBtn()">
                <a v-btnPermission="'qm_067_edi_10'" @click="handleManage(1, record)">编辑</a>
              </template>
            </MoreButton>
          </span>
        </list-table>
      </a-card>
    </div>
  </base-breadcrumb>
</template>

<script>
import OrgTreeSelect from '@/components/OrgTreeSelect'
import BasePage from '@/views/basePage'
import { qualityApiUrl } from '@/api/config.js'
import Selector from '@/components/Select/Selector' // 公共下拉框
import SelectProjectStatus from '@/views/quality/components/SelectProjectStatus' // 项目状态
import { riskGradeTable, riskGrade, riskGradeGather } from '@/api/quality/riskGrade' // api
const columns100 = [
  {
    title: '序号',
    width: '80px',
    dataIndex: 'index',
    customRender(text, record, index) {
      return index + 1
    }
  },
  {
    title: '分公司',
    ellipsis: true,
    dataIndex: 'branchComName'
  },
  {
    title: '项目名称',
    ellipsis: true,
    dataIndex: 'projectName'
  },
  {
    title: '过程检查与考核评分',
    ellipsis: true,
    dataIndex: 'processYearAverage'
  },
  {
    title: '竣工检查与考核评分',
    ellipsis: true,
    dataIndex: 'finishAverage'
  },
  {
    title: '综合得分',
    ellipsis: true,
    dataIndex: 'compositeScore'
  },
  {
    title: '填报时间',
    ellipsis: true,
    dataIndex: 'fillerDate'
  },
  {
    title: '填报人',
    ellipsis: true,
    dataIndex: 'fillerEmployeeName'
  },
  {
    title: '状态',
    dataIndex: 'statusName',
  },
  {
    title: '操作',
    dataIndex: 'action',
    width: '180px',
    align: 'center',
    scopedSlots: { customRender: 'action' }
  }
]
const columns0 = [
  {
    title: '序号',
    width: '80px',
    dataIndex: 'index',
    customRender(text, record, index) {
      return index + 1
    }
  },
  {
    title: '分公司',
    ellipsis: true,
    dataIndex: 'branchComName'
  },
  {
    title: '项目名称',
    ellipsis: true,
    dataIndex: 'projectName'
  },
  {
    title: '年度',
    ellipsis: true,
    dataIndex: 'gradeYear',
    customRender(text, record, index) {
      return text ? text + '年' : ''
    }
  },
  {
    title: '考核得分',
    ellipsis: true,
    dataIndex: 'percentileSystemScore'
  },
  {
    title: '评价时间',
    ellipsis: true,
    dataIndex: 'fillerDate'
  },
  {
    title: '评价类型',
    ellipsis: true,
    dataIndex: 'typeName'
  },
  {
    title: '评价人',
    ellipsis: true,
    dataIndex: 'gradeEmployeeName'
  },
  {
    title: '状态',
    dataIndex: 'statusName',
  },
  {
    title: '操作',
    dataIndex: 'action',
    width: '180px',
    align: 'center',
    scopedSlots: { customRender: 'action' }
  }
]
const columns1 = [
  {
    title: '序号',
    width: '80px',
    dataIndex: 'index',
    customRender(text, record, index) {
      return index + 1
    }
  },
  {
    title: '分公司',
    ellipsis: true,
    dataIndex: 'branchComName'
  },
  {
    title: '项目名称',
    ellipsis: true,
    dataIndex: 'projectName'
  },
  {
    title: '考核得分',
    ellipsis: true,
    dataIndex: 'percentileSystemScore'
  },
  {
    title: '评价时间',
    ellipsis: true,
    dataIndex: 'fillerDate'
  },
  {
    title: '评价类型',
    ellipsis: true,
    dataIndex: 'typeName'
  },
  {
    title: '评价人',
    ellipsis: true,
    dataIndex: 'gradeEmployeeName'
  },
  {
    title: '状态',
    dataIndex: 'statusName',
  },
  {
    title: '操作',
    dataIndex: 'action',
    width: '180px',
    align: 'center',
    scopedSlots: { customRender: 'action' }
  }
]
export default {
  name: 'a' + Date.now(),
  extends: new BasePage(),
  components: {
    
  },
  data() {
    this.columns0 = columns0
    this.columns1 = columns1
    this.columns100 = columns100
    return {
      selectedRowKeys0: [],
      selectedRowKeys1: [],
      selectedRowKeys100: [],
      selectedRows0: [],
      selectedRows1: [],
      selectedRows100: [],
      exportExcelLoading: {0: false, 1: false}, // 导出加载控件
      rate: ['', ''], // 导出进度
      exportLoading: {0: false, 1: false}, // 导出加载控件
      qualityApiUrl,
      queryParam: {}, // 查询参数
      cate: '100',
      totalSize0: 0,
      totalSize1: 0,
      totalSize100: 0,
      // 加载数据方法 必须为 Promise 对象
      loadData: (parameter) => {
        if (this.cate == '100') {
          const requestParameters = Object.assign(parameter, this.queryParam)
          return riskGradeGather.postList(requestParameters).then((res) => {
            if (res.data) {
              this.totalSize100 = res.totalSize
            }
            this.tabStatus = true
            return res
          }).catch(() => {
            this.tabStatus = true
          })
        } else {
          const requestParameters = Object.assign({ cate: this.cate }, parameter, this.queryParam)
          return riskGrade.postList(requestParameters).then((res) => {
            if (res.data) {
              if (this.cate == '0') {
                this.totalSize0 = res.totalSize
              } else {
                this.totalSize1 = res.totalSize
              }
              
            }
            this.tabStatus = true
            return res
          }).catch(() => {
            this.tabStatus = true
          })
        }
      },
      tabList: [
        {
          name: '汇总',
          id: '100',
        },
        {
          name: '过程评价',
          id: '0',
        },
        {
          name: '竣工评价',
          id: '1',
        },
      ], // 标签页列表
      tabStatus: false, // 标签页切换状态
      visible: false, // 确认框loading
    }
  },
  computed: {
    cateName() {
      return this.tabList.filter(item => item.id === this.cate)[0].name
    },
    searchArr() {
      const list = [
        // 搜索框
        {
          name: '所属单位',
          valueKey: 'searchQuery',
          type: OrgTreeSelect,
        },
        {
          name: '项目状态',
          type: SelectProjectStatus,
          valueKey: 'projectStatus',
        },
      ]
      if (this.cate === '100') {
        list.push({
          name: '填报时间',
          type: 'dateRange',
          value: 'date',
          attr: {
            rangeFormat: ['startDate', 'endDate']
          }
        })
      } else {
        list.push({
          valueKey: 'typeId',
          type: Selector,
          name: '评价类型',
          attr: {
            type: '64'
          }
        })
        list.push({
          name: '评价时间',
          type: 'dateRange',
          value: 'date',
          attr: {
            rangeFormat: ['startDate', 'endDate']
          }
        })
      }
      return list
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.cate = '100'
      this.initTable()
    })
  },
  methods: {
    onSelectChange(selectedRowKeys, selectedRows) {
      if (this.cate === '100') {
        this.selectedRowKeys100 = selectedRowKeys
        this.selectedRows100 = selectedRows
      } else if (this.cate === '0') {
        this.selectedRowKeys0 = selectedRowKeys
        this.selectedRows0 = selectedRows
      } else {
        this.selectedRowKeys1 = selectedRowKeys
        this.selectedRows1 = selectedRows
      }
    },
    /**
     * @description: 导出word
     * @param {*} datas：选中项
     */
     exportExcel(index) {
      if (index) {
        this.exportExcelLoading[index] = true
        if (this.cate == '100') {
          const requestParameters = Object.assign({}, {pageNo: 1, pageSize: this.totalSize100}, this.queryParam)
          return riskGradeGather.postList(requestParameters).then((res) => {
            this.$refs.exportAll && this.$refs.exportAll.setDataAndGenerate(res.data)
            this.exportExcelLoading[index] = false
          }).catch(() => {
            this.exportExcelLoading[index] = false
          })
        } else {
          const requestParameters = Object.assign({}, {pageNo: 1, pageSize: this.cate == '0' ? this.totalSize0 : this.totalSize1, cate: this.cate}, this.queryParam)
          return riskGrade.postList(requestParameters).then((res) => {
            this.$refs.exportAll && this.$refs.exportAll.setDataAndGenerate(res.data)
            this.exportExcelLoading[index] = false
          }).catch(() => {
            this.exportExcelLoading[index] = false
          })
        }
      } else {
        if (this.cate == '100') {
          if (this.selectedRows100.length > 0) {
            this.exportExcelLoading[index] = true
            this.$refs.exportSelect && this.$refs.exportSelect.setDataAndGenerate(this.selectedRows100)
            this.exportExcelLoading[index] = false
          } else {
            this.$message.warning('请选择需要导出的数据')
          }
        } else if (this.cate == '0') {
          if (this.selectedRows0.length > 0) {
            this.exportExcelLoading[index] = true
            this.$refs.exportSelect && this.$refs.exportSelect.setDataAndGenerate(this.selectedRows0)
            this.exportExcelLoading[index] = false
          } else {
            this.$message.warning('请选择需要导出的数据')
          }
        } else {
          if (this.selectedRows1.length > 0) {
            this.exportExcelLoading[index] = true
            this.$refs.exportSelect && this.$refs.exportSelect.setDataAndGenerate(this.selectedRows1)
            this.exportExcelLoading[index] = false
          } else {
            this.$message.warning('请选择需要导出的数据')
          }
        }
        
      }
    },
    /**
     * @description: 导出word
     * @param {*} index：导出类型：0 选中，1 全部
     * @param {*} datas：选中项
     */
     exportWord(index, datas) {
      let args = {}
      if (datas?.length) {
        args.ids = datas
      } else {
        args = this.queryParam
      }
      let cate = this.cate
      if (cate != '100') {
        args.cate = cate
      }
      this.exportLoading[index] = true
      let quest = null
      if (cate == '100') {
        quest = riskGradeGather
      } else {
        quest = riskGrade
      }
      quest
        .batchPrint(args)
        .then((res) => {
          if (res.code === 200) {
            // 格式化名称，防止重名被覆盖
            res.data.forEach((i,idx) => {
              i.name = (Number(idx) + 1)  + '.' + i.name
            })
            this.exportPointInfo(res.data, '项目质量风险评价' + this.cateName)
          }
          this.exportLoading[index] = false
        })
        .catch(() => {
          this.exportLoading[index] = false
          this.rate[index] = ''
        })
    },
    callback(key) {
      if (this.tabStatus) {
        this.tabStatus = false
        this.$refs.table.refresh(true)
      }
      this.initTable()
    },
    initTable() {
      let columns = []
      if (this.cate == '100') {
        columns = columns100
      } else if (this.cate == '0') {
        columns = columns0
      } else {
        columns = columns1
      }
      columns = columns.filter(item => item.dataIndex != 'action' && item.dataIndex != 'index')
      this.$refs.exportSelect && this.$refs.exportSelect.tableToExcelFile({columns })
      this.$refs.exportAll && this.$refs.exportAll.tableToExcelFile({columns })
    },
    /**
     * 搜索
     */
    search(value) {
      value && (this.queryParam = value)
      this.$refs.table.refresh(true)
    },
    /**
     * 删除草稿
     */
    handleRemove(record) {
      this.$confirm({
        title: '温馨提示',
        content: '确定删除草稿？',
        onOk: () => {
          return riskGradeGather.del(record.id).then((res) => {
            this.$message.success('删除成功！')
            // 关闭当前页
            this.search()
          })
          // .catch((res) => {
          //   this.$message.warning('删除失败！')
          // })
        }
      })
    },
    /**
     * 操作栏
     */
    handleManage(type, record) {
      this.editModel = type
      let query = {
        editModel: type,
        cate: this.cate
      }
      if (record && record.id) {
        query.id = record.id
      }
      this.$router.push({
        name: this.cate === '100' ? '/quality/riskAssessmentProject/summary' : '/quality/riskAssessmentProject/info',
        query
      })
    }
  }
}
</script>
